package com.heima.search.service.impl;

import com.heima.common.dto.ResponseResult;
import com.heima.search.dto.ApArticleSearchDto;
import com.heima.search.entity.ApAssociateWords;
import com.heima.search.repository.AssociateWordsRepository;
import com.heima.search.service.IApAssociateWordsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ApAssociateWordsServiceImpl implements IApAssociateWordsService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private AssociateWordsRepository wordsRepository;

    /**
     * 加载联想词
     * @param dto
     * @return
     */
    @Override
    public ResponseResult<List<ApAssociateWords>> search(ApArticleSearchDto dto) {
        //用户传入关键词的前面部分 补全后面的词
        //select * from tb where like 'word%'
//        Query query = new Query();
//        query.addCriteria(Criteria.where("associateWords").regex("/"+dto.getSearchWords()+".*/"));
        //分页查询 按照创建时间倒序排序
        //List<ApAssociateWords> words = wordsRepository.findByAssociateWordsStartingWith(dto.getSearchWords());
        Pageable page = PageRequest.of(0,dto.getSize(), Sort.Direction.DESC,"createdTime");
        List<ApAssociateWords> words = wordsRepository.findByAssociateWordsStartingWith(dto.getSearchWords(), page);
        return ResponseResult.okResult(words);
    }
}
